package com.swinw.asumall.product.service.impl;

import com.swinw.asumall.product.entity.SkuImagesEntity;
import com.swinw.asumall.product.entity.SpuInfoDescEntity;
import com.swinw.asumall.product.entity.SpuInfoEntity;
import com.swinw.asumall.product.service.*;
import com.swinw.asumall.product.vo.ItemSaleAttrsVo;
import com.swinw.asumall.product.vo.SkuItemVo;
import com.swinw.asumall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swinw.common.utils.PageUtils;
import com.swinw.common.utils.Query;

import com.swinw.asumall.product.dao.SkuInfoDao;
import com.swinw.asumall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 多条件分页查询sku信息
     * key: 华为 ID 或 sku_name
     * catelogId: 225 三级分类ID
     * brandId: 6 品牌ID
     * min: 5000 最小价格
     * max: 6000 最大价格
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        //三级分类ID
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)){ //catelogId.equals("0")
            try {
                int logId = Integer.parseInt(catelogId);
                if(logId > 0){
                    queryWrapper.eq("catalog_id",logId);
                }
            }catch (Exception e){

            }
        }

        //品牌ID
        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)){//brandId.equals("0")
            try {
                int bId = Integer.parseInt(brandId);
                if(bId > 0){
                    queryWrapper.eq("brand_id",bId);
                }
            }catch (Exception e){

            }
        }

        //关键字搜索
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and((warpper)->{
                warpper.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        //最小价格
        String minPrice = (String) params.get("min");
        if(!StringUtils.isEmpty(minPrice)){//!minPrice.equals("0")
            try{
                BigDecimal bigDecimal = new BigDecimal(minPrice);
                if(bigDecimal.compareTo(BigDecimal.ZERO) > 0){
                    queryWrapper.ge("price",bigDecimal);
                }
            }catch (Exception e){
            }

        }

        //最大价格
        String maxPrice = (String) params.get("max");
        if(!StringUtils.isEmpty(maxPrice)){//!maxPrice.equals("0")
            try{
                BigDecimal bigDecimal = new BigDecimal(maxPrice);
                if(bigDecimal.compareTo(BigDecimal.ZERO) > 0){
                    queryWrapper.le("price",bigDecimal);
                }
            }catch (Exception e){
            }
        }

        //查询
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 通过spuId查询sku信息
     * @param spuId
     * @return
     */
    @Override
    public List<SkuInfoEntity> selectSkuInfoBySpuId(Long spuId) {
        List<SkuInfoEntity> infoEntities = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return infoEntities;
    }

    /**
     * 使用异步编排查询获取商品详情页信息
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo getSaleItemBySkuId(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();
        //1、封装SkuInfo信息
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity byId = this.getById(skuId);
            skuItemVo.setSkuInfoEntity(byId);
            return byId;
        }, executor);

        //2、封装SkuImg信息
        CompletableFuture<Void> imgFutrue = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> images = skuImagesService.getImgsBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        //3、封装Spu销售属性组合
        CompletableFuture<Void> saveFutrue = skuInfoFuture.thenAcceptAsync((res) -> {
            List<ItemSaleAttrsVo> attrSale = skuSaleAttrValueService.getSkuSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(attrSale);
        }, executor);

        //4、查询Spu的介绍
        CompletableFuture<Void> spuInfoDescFutrue = skuInfoFuture.thenAcceptAsync((res) -> {
            SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setSpuInfoDescEntity(spuInfoDesc);
        }, executor);

        //5、封装Spu的规格参数信息
        CompletableFuture<Void> groupFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, executor);

        //6、等上面的任务都执行完成，就返回结果
        CompletableFuture.allOf(imgFutrue,saveFutrue,spuInfoDescFutrue,groupFuture).get();

        return skuItemVo;
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        return baseMapper.getSpuInfoBySkuId(skuId);
    }

}